﻿using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using BTBookList.BookListManagement.Books.Dtos;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;

namespace BTBookList.BookListManagement.Books
{
    public class BookAppService : BTBookListAppServiceBase, IBookAppService
    {
        private readonly IRepository<Book, long> _bookRepository;

        public BookAppService(IRepository<Book,long> bookRepository)
        {
            _bookRepository = bookRepository;
        }


        public async Task<PagedResutDto<BookListDto>> GetPageBook(GetBookInput Input)
        {
            var query = _bookRepository.GetAll().AsNoTracking().WhereIf(!Input.FilterText.IsNullOrWhiteSpace(),
                a => a.Name.Contains(Input.FilterText));
            var count = await query.CountAsync();
            var entityList = await query.OrderBy(Input.Sorting).PageBy(Input).ToListAsync();
            //autoMapper
            var entityListDtos = entityList.MapTo<List<BookListDto>>();

            return new PagedResutDto<BookListDto>(count, entityListDtos);
        }

        public async Task CreateOrUpdateBook(CreateOrUpdateBookInput input)
        {
            if (input.Book.Id.HasValue)
            {
                //修改
                await UpdateBook(input.Book);
            }
            else
            {
                //新增
                await CreateBook(input.Book);
            }

        }

        protected virtual async Task<BookEditDto> CreateBook(BookEditDto input)
        {
            var entity = input.MapTo<Book>();
            await _bookRepository.InsertAsync(entity);

            var dto = entity.MapTo<BookEditDto>();
            return dto;

        }
      protected virtual async Task UpdateBook(BookEditDto input)
        {
            var entity = await _bookRepository.GetAsync(input.Id.Value);

            input.MapTo(entity);

            await _bookRepository.UpdateAsync(entity);


        }

        public async  Task DeleteBook(EntityDto<long> input)
        {
          await  _bookRepository.DeleteAsync(input.Id);
        }

        public async Task BatchDeleteBook(List<long> input)
        {
            await _bookRepository.DeleteAsync(a=> input.Contains(a.Id));
        }
    }
}
